package com.example.intermediateactivity;

import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Spinner;

import androidx.activity.EdgeToEdge;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.graphics.Insets;
import androidx.core.view.ViewCompat;
import androidx.core.view.WindowInsetsCompat;

import com.example.intermediateactivity.utils.ToastHelper;

public class SpinnerDropdown extends AppCompatActivity implements AdapterView.OnItemSelectedListener {

    private final static String[] fruitArray = new String[]{
            "苹果",
            "香蕉",
            "橘子",
            "梨子",
            "桃子",
            "西瓜",
            "榴莲",
            "芒果",
    };
    private Spinner spDropdown;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_spinner_dropdown);

        // 列表容器
        spDropdown = findViewById(R.id.sp_dropdown);
        // 创建一个列表适配器提供同意的方法，将列表元素、列表数据、给适配器，列表容器通过适配器创建列表
        ArrayAdapter<String> listAdapter = new ArrayAdapter<>(this, R.layout.select_item, fruitArray);
        // 列表容器设置适配器
        spDropdown.setAdapter(listAdapter);
        // 默认选择第0项
        spDropdown.setSelection(0);
        // 监听选中某项事件
        spDropdown.setOnItemSelectedListener(this);


        // 对话框模式的下拉列表
        Spinner spDialog = findViewById(R.id.sp_dialog);
        ArrayAdapter<String> dialogAdapter = new ArrayAdapter<String>(this, R.layout.select_item, fruitArray);
        spDialog.setAdapter(dialogAdapter);
        spDialog.setPrompt("选择一个水果吧");
        spDialog.setSelection(0);
        spDialog.setOnItemSelectedListener(this);
    }

    @Override
    public void onItemSelected(AdapterView<?> adapterView, View view, int index, long l) {
        ToastHelper.show(this, "您选中的是" + fruitArray[index]);
    }

    @Override
    public void onNothingSelected(AdapterView<?> adapterView) {

    }
}